package com.example.demoofimagedownloadapp.model.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author ts
 */
public class HttpAsyncTask extends AsyncTask<String,Integer,Bitmap> {

    private Bitmap mBitmap;
    private String mURL = null;
    private ImageView mView = null;

    public HttpAsyncTask (String str, ImageView view) {
        mURL = str;
        mView = view;
    }
    @Override
    protected Bitmap doInBackground(String... strings) {
        mBitmap = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream inputStream = null;
        String url_path = mURL;
        try {
            URL url = new URL(url_path);
            inputStream = url.openStream();

            //  BitmapFactory.decodeStream(inputStream) Method
//            mBitmap = BitmapFactory.decodeStream(inputStream);

            URLConnection openConnection = new URL(url_path).openConnection();

            long file_length = openConnection.getContentLength();
            int len = 0;
            byte[] data = new byte[1024];
            //每次读取的字节
            int total_length = 0;
            // 以字节的方式读取图片数据
            while ((len = inputStream.read(data)) != -1) {
                total_length += len;
                // 计算进度
                int values = (int) ((total_length / (float) file_length) * 100);
                // 发布进度信息
                publishProgress(values);
                //发布进度，AsyncTask第二个参数类型，触发onProgressUpdate更新进度条
                outputStream.write(data, 0, len);
                //写入输出流
//                Thread.sleep(100);
            }
            byte[] result=outputStream.toByteArray();
            //将字节数组输出流转换为字节数组
            //生成二进制图片
            mBitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return mBitmap;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        mView.setImageBitmap(bitmap);
    }
}
